
package org.example.interceptor;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.example.utils.CurrentHolder;
import org.springframework.web.servlet.ModelAndView;


/*
* 令牌校验拦截器
* */

@Slf4j
@Component
public class TokenIntercept implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求URL
        String url = request.getRequestURI().toString();

        // 2.判断URL中是否包含Login 如果包含登录操作，直接放行
        if(url.contains("login")) {
            log.info("登录请求，直接放行");
            return true;
        }

        // 3.获取请求头中的令牌（token）
        String token = request.getHeader("token");

        // 4.判断令牌是否存在，如果不存在，直接返回401
        if(token == null || token.isEmpty()) {
            log.info("令牌为空，响应401");
            response.setStatus(401);
            return false;
        }

        // 5.如果令牌存在，就解析令牌
        try {
            Claims claims = JwtUtils.parseJwt(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
            log.info("当前员工ID：{}", empId);
            log.info("令牌解析成功：{}", claims);
            // 6.如果解析成功，就放行
            return true;
        } catch (Exception e) {
            // 7.如果解析失败，就返回401
            log.info("令牌解析失败，响应401");
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        // 删除ThreadLocal中的数据，防止内存泄漏
        CurrentHolder.remove();
    }
}

